package com.gongqi.org.web;

import com.gongqi.org.domain.Department;
import com.gongqi.org.query.DepartmentQuery;
import com.gongqi.org.service.DepartmentService;
import com.gongqi.utils.PageList;
import com.gongqi.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/department")
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class controller {

    @Autowired
    private DepartmentService service;

    @GetMapping("/{id}")
    public R loadById(@PathVariable("id") Long id){
        try {
            Department department = service.getById(id);
            return R.me().setResult(department);
        } catch (Exception e) {
            e.printStackTrace();
            return R.me().setSuccess(false).setMessage("获取一个失败"+e.getMessage());
        }
    }
    @GetMapping
    public R loadAll(){
        try {
            List<Department> list = service.getAll();
            return R.me().setResult(list);
        } catch (Exception e) {
            e.printStackTrace();
            return R.me().setSuccess(false).setMessage("获取所有失败"+e.getMessage());
        }
    }
    @PutMapping
    @Transactional
    public R addOrUpdate(@RequestBody Department department){
        try {
            if (department.getId() == null)
                service.add(department);
            else
                service.update(department);
            return R.me().setResult(department);
        } catch (Exception e) {
            e.printStackTrace();
            return R.me().setSuccess(false).setMessage("保存失败"+e.getMessage());
        }
    }

    @DeleteMapping("/{id}")
    @Transactional
    public R del(@PathVariable("id") Long id ){
        try {
            service.del(id);
            return R.me();
        } catch (Exception e) {
            e.printStackTrace();
            return R.me().setSuccess(false).setMessage("删除失败"+e.getMessage());
        }
    }
    //分页查询
    @PostMapping

    public R queryPage(@RequestBody DepartmentQuery query){
        try {
            PageList<Department> pageList = service.queryPage(query);
            return R.me().setResult(pageList);
        } catch (Exception e) {
            e.printStackTrace();
            return R.me().setSuccess(false).setMessage("分页查询失败"+e.getMessage());
        }
    }
}
